import {listPlan} from "../api/plan";
import {PlanMapper} from "../mappers/PlanMapper";
import {createLogger, useStore} from "vuex";
import {Plan} from "../sql/domin";
import {reactive, ref, watch} from "vue";
import {loginService} from "./login";
import {onLoad} from "@dcloudio/uni-app";

export function PlanDataHandle(){

    const {getNetWorkType} = loginService()

    const store = useStore()

    const role = store.getters.role

    const plans = ref<Plan[]>()

    const refreshPlan = async () => {
        let res = await listPlan()
        let list = res.data.data as Plan[]
        //(res)
        await PlanMapper.deletePlanByRole(role)
        //(list)
        if (list.length != 0){
            list.forEach(it=>{
				delete it.params
                PlanMapper.insertPlan(it).catch(err=>{console.log(err)})
            })

        }
    }

    const getPlanList = async ()=>{
        plans.value = (await PlanMapper.selectPlanListByRole(role)) as Plan[]
    }

    getPlanList()

    const content = reactive([
        {
            iconPath: '/static/refrash.png',
            selectedIconPath: '/static/refrash-active.png',
            text: '刷新',
            active: false
        },
    ])

    const selectIndex = ref(0)

    watch(selectIndex, (newVal, oldVal) => {
        content[newVal].active = true
        content[oldVal].active = false
    })

    const handleClick = async (e: any) => {
        selectIndex.value = e.index
        switch (e.index){
            case 0:
                uni.showToast({
                    icon:'none',
                    title:'正在检查网络'
                })
                if (await getNetWorkType()){
                    uni.showLoading({
                        title:'网络连接成功,正在拉取数据'
                    })
                    refreshPlan().then(()=>{
                        getPlanList()
                    })
                    uni.hideLoading()
                }
                break
        }
    }

    const handleLook = (id:number)=>{
        uni.navigateTo({
            url:'/pages/plan/form?id='+id
        })
    }

    return{
        refreshPlan,
        getPlanList,
        plans,
        content,
        handleClick,
        handleLook
    }
}

export function PlanFormHandle(){

    const plan = ref<Plan>()

    onLoad(async (props)=>{
        //("props==",props)
        if (props.id != null){
            plan.value = await getPlanInfo(Number.parseInt(props.id))
        }
    })

    const getPlanInfo = async (id:number)=>{
        return ((await PlanMapper.selectPlanById(id)) as Plan[])[0]
    }

    return{
        plan
    }
}
